'use strict';
const app = getApp()
const HOST = app.baseURL


import Toast from '../miniprogram_npm/@vant/weapp/toast/toast'
var WSCoordinate = require('WSCoordinate.js')

let a = {

  RandNum: function (n) {
    var rnd = "";
    for (var i = 0; i < n; i++)
      rnd += Math.floor(Math.random() * 10);
    return rnd;
  },
  checkPhone1: function (tel) {
    var pattern = /(^[0-9]{3,4}\[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)/;
    if (pattern.test(tel)) {
      return true;
    } else {
      return false;
    }
  },
  checkPhone: function (phone) {
    let isPhone = /^([0-9]{3,4})?[0-9]{7,8}$/;
    let isMob = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
    let value = phone;
    if (isMob.test(value) || isPhone.test(value)) {
      return true;
    } else {
      return false;
    }
  },
  IdentityCodeValid: function (code) {
    var city = {
      11: "北京",
      12: "天津",
      13: "河北",
      14: "山西",
      15: "内蒙古",
      21: "辽宁",
      22: "吉林",
      23: "黑龙江 ",
      31: "上海",
      32: "江苏",
      33: "浙江",
      34: "安徽",
      35: "福建",
      36: "江西",
      37: "山东",
      41: "河南",
      42: "湖北 ",
      43: "湖南",
      44: "广东",
      45: "广西",
      46: "海南",
      50: "重庆",
      51: "四川",
      52: "贵州",
      53: "云南",
      54: "西藏 ",
      61: "陕西",
      62: "甘肃",
      63: "青海",
      64: "宁夏",
      65: "新疆",
      71: "台湾",
      81: "香港",
      82: "澳门",
      91: "国外 "
    };
    var tip = "";
    var pass = true;

    if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
      tip = "身份证号格式错误";
      pass = false;
    } else if (!city[code.substr(0, 2)]) {
      tip = "地址编码错误";
      pass = false;
    } else {
      //18位身份证需要验证最后一位校验位
      if (code.length == 18) {
        code = code.split('');
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        //校验位
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        var sum = 0;
        var ai = 0;
        var wi = 0;
        for (var i = 0; i < 17; i++) {
          ai = code[i];
          wi = factor[i];
          sum += ai * wi;
        }
        var last = parity[sum % 11];
        if (parity[sum % 11] != code[17]) {
          tip = "校验位错误";
          pass = false;
        }
      }
    }
    // if(!pass) alert(tip);
    return pass;
  },
  getDateTime: function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();

    return [year, month, day].map(function (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }).join('-') + ' ' + [hour, minute, second].map(function (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }).join(':')

  },

  getDate: function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();

    return [year, month, day].map(function (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }).join('-')

  },

  newGuid: function () //30万数据测试过，未重复
  {
    var guid = "";
    for (var i = 1; i <= 32; i++) {
      var n = Math.floor(Math.random() * 16.0).toString(16);
      guid += n;
      if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
        guid += "-";
    }
    return guid;
  },

  isJson: function (obj) {
    var isjson = typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    return isjson;
  },

  setStore: function (name, code) {
    if (typeof (code) == "undefined") code = "";
    if (this.isJson(code) || Array.isArray(code)) code = JSON.stringify(code);
    wx.setStorageSync(name, code);
  },

  getStore: function (name) {
    var value = wx.getStorageSync(name);
    if (value) {
      if ((value.length > 1) && (value.charAt(0) == '{' || value.charAt(0) == '[') &&
        (value.charAt(value.length - 1) == '}' || value.charAt(value.length - 1) == ']')) {
        value = JSON.parse(value);
      }
    } else {
      value = '';
    }
    return value;
  },

  clearStore: function (name) {
    if (name) {
      wx.removeStorageSync(name);
    } else {
      wx.clearStorageSync();
    }
  },
  jisuan(data){
    // wx.request({
    //   url: HOST + '/Index/Liquid/count_food_water',
    //   method:'POST',
    //   data:data,
    //   success: function (res) {
    //     if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 304) {
    //       resolve(res.data)
    //     } else {
    //       Toast('服务器返回状态 ' + res.statusCode)
    //       reject('服务器返回状态' + res.statusCode)
    //     }
    //   },
    // })
    return new Promise((resolve, reject) => {
      wx.request({
        url: HOST + '/Index/Liquid/count_food_water',
        data: data,
        method: "POST",
        success: function (res) {
          if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 304) {
            resolve(res.data)
          } else {
            Toast('服务器返回状态 ' + res.statusCode)
            reject('服务器返回状态' + res.statusCode)
          }
        },
        fail: function (res) {
          console.log('rece fail:' + JSON.stringify(res));
          Toast(res);
          reject(res)
        }
      })
    })
  },
  send(data, params, url) {
      data['unionid'] = app.globalData.unionid;
      data['openid'] = app.globalData.openid;
      data['userid'] = app.globalData.userid;
    // console.log('send1:' + JSON.stringify(data));

    if (params == undefined) params = {};
    if (!params.message) {
      params.message = '加载中...';
    }
    // Toast.loading({
    //   message: params.message,
    //   forbidClick: true,
    // });
    if (typeof (params.isloading) == 'undefined' || params.isloading) {
      wx.showLoading({
        title: params.message,
      })
      
    }

    var method = 'GET';
    
    if (params.method) {
      if (params.method.toUpperCase() === 'POST' || params.method.toUpperCase() === 'GET')
        method = params.method.toUpperCase();

    }
    let contentType = 'application/json'
    if(method === 'POST') {
      contentType = 'application/x-www-form-urlencoded'
    } 
    // console.log(method)
    return new Promise((resolve, reject) => {
      // console.log('---send---')
      wx.request({
        url: HOST + data.flag,
        data: data,
        method: method,
        header: {
          'content-type': contentType
        },
        success: function (res) {
          // Toast.clear();
          // console.log('rece:' + JSON.stringify(res));
          if (typeof (params.isloading) == 'undefined' || params.isloading) {
            wx.hideLoading();
            
          }

          if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 304) {
            resolve(res.data)
  
          } else {
            Toast('服务器返回状态 ' + res.statusCode)
            reject('服务器返回状态' + res.statusCode)
          }
        },
        fail: function (res) {

          console.log('rece fail:' + JSON.stringify(res));
          if (typeof (params.isloading) == 'undefined' || params.isloading) {
            wx.hideLoading();
          }
          Toast(res);

          reject(res)
        }
      })
    })
  },

  sendpic(imagePath, data, params, url) {
    if (params == undefined) params = {};
    if (!params.message) {
      params.message = '上传中...';
    }
    // Toast.loading({
    //   message: params.message,
    //   forbidClick: true,
    // });
    if (typeof (params.isloading) == 'undefined' || params.isloading) {
      wx.showLoading({
        title: params.message,
      })
      
    }

    var token = app.globalData.token;
    if (token)
      data['token'] = app.globalData.token;
    data.requst_type = 1
    return new Promise((resolve, reject) => {
      console.log('---send---')
      wx.uploadFile({
        url: HOST  + '?requst_type=1',
        filePath: imagePath,
        name: 'imgfile',
        formData: data,
        success: function (res) {
          // Toast.clear()
          console.log(res)
          if (typeof (params.isloading) == 'undefined' || params.isloading) {
            wx.hideLoading();
          }
          if (res.statusCode == 200)
            resolve(JSON.parse(res.data))
          else {
            Toast(res)
            reject('服务器返回状态' + res.statusCode)
          }
        },
        fail: function (res) {
          console.log(res)
          Toast(res)

          if (typeof (params.isloading) == 'undefined' || params.isloading) {
            wx.hideLoading();
            
          }
          reject(res)
        }
      })
    })
  },

  get(url) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: (url ? url : this.HOST_WORK),
        headers: {
          'Content-Type': 'application/json'
        },
        success: function (res) {
          resolve(res)
        },
        fail: function (res) {
          reject(res)
        }
      })
    })
  },

  json2Form(json) {
    var str = []
    for (var p in json) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]))
    }
    return str.join("&")
  },

  /**
   * 字符串转时间（yyyy-MM-dd HH:mm:ss）
   * result （分钟）
   */
  stringToDate: function (fDate) {
    var fullDate = fDate.split("-");
    return new Date(fullDate[0], fullDate[1] - 1, fullDate[2], 0, 0, 0);
  },

  chooseImages(number) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: number,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        // success(res) {
        //   // tempFilePath可以作为img标签的src属性显示图片
        //   const tempFilePaths = res.tempFilePaths
        //   console.log(tempFilePaths)
        // }
        success: function (res) {
          console.log(res)
          let image = res.tempFilePaths[0];
          let size = res.tempFiles[0].size;
          if ((size / 1000) < 2048 *　10) {
            var senddata = {};
            senddata['flag'] = '/upload/push';
            senddata['openid'] = getApp().globalData.openid;
            senddata['unionid'] = getApp().globalData.unionid;
            a.sendpic(image, senddata, {}).then(resp => {
              if (resp.code === 1) {
                console.log('图片上传成功');
                resolve(resp)
              } else {
                console.log('图片上传失败');
                Toast('图片上传失败')
                reject(resp.errmsg);
              }
            }, fail => {
              reject('登录失败：' + JSON.stringify(fail));
            })
          } else {
            Toast('图片大于20M,请重新选择')
            reject('图片过大,重新选择');
          }
        }
      })
    })

  },


  /**
   * 格式化日期
   * @param date 日期
   * @param format 格式化样式,例如yyyy-MM-dd HH:mm:ss E
   * @return 格式化后的金额
   */
  formatDate: function (date, format) {
    var v = "";
    if (typeof date == "string" || typeof date != "object") {
      return;
    }
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    var weekDay = date.getDay();
    var ms = date.getMilliseconds();
    var weekDayString = "";

    if (weekDay == 1) {
      weekDayString = "星期一";
    } else if (weekDay == 2) {
      weekDayString = "星期二";
    } else if (weekDay == 3) {
      weekDayString = "星期三";
    } else if (weekDay == 4) {
      weekDayString = "星期四";
    } else if (weekDay == 5) {
      weekDayString = "星期五";
    } else if (weekDay == 6) {
      weekDayString = "星期六";
    } else if (weekDay == 7) {
      weekDayString = "星期日";
    }

    v = format;
    //Year
    v = v.replace(/yyyy/g, year);
    v = v.replace(/YYYY/g, year);
    v = v.replace(/yy/g, (year + "").substring(2, 4));
    v = v.replace(/YY/g, (year + "").substring(2, 4));

    //Month
    var monthStr = ("0" + month);
    v = v.replace(/MM/g, monthStr.substring(monthStr.length - 2));

    //Day
    var dayStr = ("0" + day);
    v = v.replace(/dd/g, dayStr.substring(dayStr.length - 2));

    //hour
    var hourStr = ("0" + hour);
    v = v.replace(/HH/g, hourStr.substring(hourStr.length - 2));
    v = v.replace(/hh/g, hourStr.substring(hourStr.length - 2));

    //minute
    var minuteStr = ("0" + minute);
    v = v.replace(/mm/g, minuteStr.substring(minuteStr.length - 2));

    //Millisecond
    v = v.replace(/sss/g, ms);
    v = v.replace(/SSS/g, ms);

    //second
    var secondStr = ("0" + second);
    v = v.replace(/ss/g, secondStr.substring(secondStr.length - 2));
    v = v.replace(/SS/g, secondStr.substring(secondStr.length - 2));

    //weekDay
    v = v.replace(/E/g, weekDayString);
    return v;
  },
  /**
   * 计算两个日期相差几天
   * cusDate 当前时间
   * oriDate  比较时间
   * 返回 正数为cusDate>oriDate
   */
  calculateTime: function (cusDate, oriDate) {
    var cusTime = cusDate.getTime();
    var oriTime = oriDate.getTime();
    return (cusTime - oriTime) / (1000 * 60 * 60 * 24)
  },

  /**
   * JS获取距当前时间差
   *
   * @param int time JS毫秒时间戳
   *
   */
  get_time_diff: function (time) {
    let diff = '';
    let time_diff = new Date().getTime() - (time * 1000);

    // 计算相差天数
    let days = Math.floor(time_diff / (24 * 3600 * 1000));
    if (days > 3) {
      diff = a.formatDate(new Date(time * 1000), 'MM-dd HH:mm')
    } else if (days < 4 && days > 0) {
      diff = days + '天前';
    } else if (days < 1) {
      //计算相差小时数
      let leave1 = time_diff % (24 * 3600 * 1000);
      let hours = Math.floor(leave1 / (3600 * 1000));
      if (hours > 0) {
        diff = hours + '小时前';
      } else {
        // 计算相差分钟数
        let leave2 = leave1 % (3600 * 1000);
        let minutes = Math.floor(leave2 / (60 * 1000));
        console.log("minutes" + minutes)
        if (minutes < 11) {
          diff = '刚刚';
        } else {
          diff = minutes + '分前';
        }
      }

    }
    return diff;
  },

  //数组对象去重
  arrayUnique: function (arr, name) {
    var hash = {};
    return arr.reduce(function (item, next) {
      hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
      return item;
    }, []);
  },

  checkIdentity() {
    let runFalse = false;
    let userType = getApp().globalData.usertype;
    if (userType == -1) {
      runFalse = true;
    }
    return runFalse
  },
  getFromId(fromId, formType, func) {
    //表单类型1创建项目2用户认证3项目约谈4申请入驻/合伙人认证5评价通知6评价回复通知7评论回复8报名取消9报名成功
    return new Promise((resolve, reject) => {
      var senddata = {};
      senddata['flag'] = 'chat/saveformid';
      senddata['openid'] = getApp().globalData.openid;
      senddata['unionid'] = getApp().globalData.unionid;
      senddata['form_id'] = fromId;
      senddata['form_type'] = formType;
      a.send(senddata, {}).then(resp => {
        resolve(fromId)
      }, fail => {
        resolve(fromId)
      })
    })
  },

  throttle: function (fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
      gapTime = 1500
    }

    let _lastTime = null

    // 返回新的函数
    return function () {
      let _nowTime = +new Date()
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
        fn.apply(this, arguments) //将this和参数传给原函数
        _lastTime = _nowTime
      }
    }
  },

  /*文件大小转换*/
  sizeTostr:function (size) {
    var data = "";
    if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
        data = size.toFixed(2) + "B";
    } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
        data = (size / 1024).toFixed(2) + "KB";
    } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
    } else { //其他转化成GB
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }
    var sizestr = data + "";
    var len = sizestr.indexOf("\.");
    var dec = sizestr.substr(len + 1, 2);
    if (dec == "00") {//当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
    }
    return sizestr;
  },

  //定位
  getloc: function (succ, fail) {
    let that = this;
    let BMap = app.globalData.BMap;
    wx.getLocation({
      type: 'gcj02',//'wgs84',
      success: function (res) {
        console.log(res)
        let currpoint = WSCoordinate.transformFromGCJToBaidu(res.latitude, res.longitude);
        console.log(currpoint)
        app.globalData.currpoint = currpoint;
        BMap.regeocoding({
          location: currpoint.latitude + ',' + currpoint.longitude,
          success: function (res) {
            console.log(res)
            app.globalData.address = res.originalData.result.addressComponent
            app.globalData.currentCityCode = res.originalData.result.addressComponent.adcode
            app.globalData.dingweiflag = true
            if( succ ) succ()
          },
          fail: function () {
            wx.showToast({title: '请检查位置服务是否开启' })
            app.globalData.dingweiflag = false
            if( fail ) fail()
          },
        });
      },
      fail: function () {
        console.log('小程序得到坐标失败')
        wx.showToast({title: '小程序定位失败' })
        app.globalData.dingweiflag = false
        if( fail ) fail()
      }
    })
  },

  checkurl:function(url){
    let images = url
    if( !images ) return '';
    if( images  instanceof Array ){
      for(let p in images){
        if(!images[p]) images[p]=''
        else{
          images[p] = images[p].replace(/picdata/g,app.ossdir)
          if( images[p].substr(0,4)!='http' ){
            if( images[p].indexOf('images')==-1){
              if( images[p].substr(0,1)=='/')
              images[p] = app.imageBaseURL+images[p]+app.imageResizeParams
              else
              images[p] = app.imageBaseURL+'/'+images[p]+app.imageResizeParams
            }else{
              images[p] = app.imageURL+images[p]
            }
          }
        }
      }
      return images
    }else{
      if( url.substr(0,4)!='http' ){
        url = url.replace(/picdata/g,app.ossdir)
        if( url.indexOf('images')==-1){
          if( url[0]=='/')
          return app.imageBaseURL+url+app.imageResizeParams
          else
          return app.imageBaseURL+'/'+url+app.imageResizeParams
        }else{
          return app.imageURL+url
        }
      }else return url;
    }
  },

  isauth:function(){
    if(!app.globalData.userInfo || !app.globalData.userInfo.name)
       return false
    else 
       return true
  },

  decodeurl:function(scene){
    if(!scene) return ''
    let str = decodeURIComponent(scene);
    let ss = str.split('&');
    let obj = {};
    for( let i=0;i<ss.length;i++ ){
      let s = ss[i].split('=');
      obj[s[0]] = s[1];
    }
    return obj
  },

  strcharacterDiscode:function(str){
      // 加入常用解析
      str = str.replace(/&nbsp;/g, ' ');
      str = str.replace(/&quot;/g, "'");
      str = str.replace(/&amp;/g, '&');
      // str = str.replace(/&lt;/g, '‹');
      // str = str.replace(/&gt;/g, '›');

      str = str.replace(/&lt;/g, '<');
      str = str.replace(/&gt;/g, '>');
      str = str.replace(/&#8226;/g, '•');

      return str;
  },

  sendshare:function(id,type){
    let data={}
    data['flag'] = 'share'
    data['id'] = id
    data['type'] = type
    this.send(data,{"isloading":false}).then(
      (result)=>{
        console.log(result)
      },(fail)=>{
        console.log(fail)
      }
    )
  }

};
module.exports = a;